package com.yumis.service.modules.car.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yumis.service.common.enums.HttpState;
import com.yumis.service.common.exception.GlobalException;
import com.yumis.service.common.vo.Page;
import com.yumis.service.common.vo.Response;
import com.yumis.service.model.pojo.Car;
import com.yumis.service.modules.car.mapper.CarMapper;
import com.yumis.service.modules.car.service.CarService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class CarServiceImpl implements CarService {
    @Resource
    private CarMapper carMapper;
    @Override
    public Page<Car> queryCar(Integer page, Integer rows) {
        PageHelper.startPage(page,rows);
        Example example = new Example(Car.class);
        example.setOrderByClause("create_time desc");
        List<Car> carList=carMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(carList)){
            throw new GlobalException(Response.buildResponse(HttpState.DATA_NOT_FOUNT));
        }
        PageInfo<Car> info = new PageInfo<>(carList);
        return new Page<>(info.getTotal(),info.getPages(),carList);
    }

    @Override
    public void updateCar(Car car) {
        car.setUpdateTime((int) (System.currentTimeMillis()/1000));
        int i=carMapper.updateByPrimaryKeySelective(car);
        if (i !=1){
            throw new GlobalException(Response.buildResponse(HttpState.UPDATE_ERROR));
        }
    }

    @Override
    public void deleteByIdCar(Long id) {
        int i=carMapper.deleteByPrimaryKey(id);
        if (i !=1){
            throw new GlobalException(Response.buildResponse(HttpState.DELETE_ERROR));
        }
    }

    @Override
    public void deleteCar(Long[] ids) {
        for (Long id:ids){
            int i=carMapper.deleteByPrimaryKey(id);
            if (i !=1){
                throw new GlobalException(Response.buildResponse(HttpState.DELETE_ERROR));
            }
        }
    }

    @Override
    public void addCar(Car car) {
        car.setCreateTime((int) (System.currentTimeMillis()/1000));
        car.setUpdateTime((int) (System.currentTimeMillis()/1000));
        int i=carMapper.insertSelective(car);
        if (i !=1){
            throw new GlobalException(Response.buildResponse(HttpState.CREATED_FAILED));
        }
    }

    @Override
    public List<Car> queryByUserCar(Long userId) {
        Car car=new Car();
        car.setUserId(userId);
        List<Car> carList=carMapper.select(car);
        if (CollectionUtils.isEmpty(carList)){
            throw new GlobalException(Response.buildResponse(HttpState.DATA_NOT_FOUNT));
        }
        return carList;
    }
}
